package com.zyk.scaffold.core.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.ArrayList;
import java.util.List;

/**
 * redis 计数器限流组件
 */
@Slf4j
public class SimpleCountRedisLimitComponent {

    private static final String REDIS_LIMIT_KEY = "limit:simple-count:";

    private StringRedisTemplate stringRedisTemplate;

    public SimpleCountRedisLimitComponent(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();

    {
        redisScript.setScriptSource(new ResourceScriptSource(
                new ClassPathResource("META-INF/scripts/simple-count-number-limiter.lua")));
        redisScript.setResultType(Long.class);
    }

    /**
     * 获取key令牌，true 获取成功、false 获取失败
     *
     * @param key        识别key
     * @param limitCount 允许数量
     * @param seconds    时间窗大小
     * @return
     */
    public boolean tryAccess(String key, int limitCount, int seconds) {
        List<String> keys = new ArrayList<>();
        keys.add(REDIS_LIMIT_KEY + key);
        Long count = stringRedisTemplate.execute(redisScript, keys, String.valueOf(limitCount), String.valueOf(seconds));
        if (count != 0) {
            return true;
        } else {
            return false;
        }
    }
}
